package org.snia.server.rs;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;

import org.snia.cdmi.ErrorCodes;
import org.snia.cdmi.Headers;
import org.snia.cdmi.auth.Principal;
import org.snia.cdmi.exception.UnauthorizedException;

public class AbstractResource {

	@Context
	private HttpHeaders headers;
	
	private Principal principal;
	
	protected Principal getPrincipal(){
		if(principal == null){
			String authorization = headers.getRequestHeader(Headers.AUTHORIZATION)
					.get(0);
			System.out.println(authorization);
			String accessKey = null;
			if (authorization != null) {
				int i = authorization.indexOf(" ");
				int j = authorization.indexOf(":");
				accessKey = authorization.substring(i + 1, j);
			} else {
				throw new UnauthorizedException(ErrorCodes.InvalidSecurity);
			}
			principal = new Principal(accessKey);
		}
		return principal;
	}
}
